﻿// 开发者:micropu
// 公司:佛山远钧智慧科技有限公司

using Admin.NET.Application.SysncService.PlatFormSync;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin.NET.Application;

/// <summary>
/// 平台在线任务管理
/// </summary>
public class PlatFormJobManager : IPlatFormJobManager
{
    // 可能被多个线程同时访问，你需要确保线程安全。一种实现方法是使用线程安全的集合，ConcurrentDictionary
    public static readonly ConcurrentDictionary<string, PassDevice> PlatformOnlineDevicesDic = new ConcurrentDictionary<string, PassDevice>();
    public static readonly SemaphoreSlim semaphore = new SemaphoreSlim(1); // 信号量，用于控制并发访问
    public static bool isRunning = false; // 是否正在运行

    /// <summary>
    /// 添加设备
    /// </summary>
    /// <param name="deviceSn"></param>
    /// <param name="device"></param>
    public void AddDevice(string deviceSn, PassDevice device)
    {
        PlatformOnlineDevicesDic.TryAdd(deviceSn, device); // 如果设备已经存在，TryAdd 方法会返回 false
    }

    /// <summary>
    /// 根据设备SN获取设备
    /// </summary>
    /// <param name="deviceSn"></param>
    /// <returns></returns>
    public PassDevice GetDevice(string deviceSn)
    {
        PlatformOnlineDevicesDic.TryGetValue(deviceSn, out PassDevice device);
        return device; // 如果没有找到设备，返回null
    }

    /// <summary>
    /// 移除设备
    /// </summary>
    /// <param name="deviceSn"></param>
    public void RemoveDevice(string deviceSn)
    {
        // // 尝试从字典中移除指定键的值，并将移除的值存储在变量 removedDevice 中
        if (PlatformOnlineDevicesDic.TryRemove(deviceSn, out PassDevice removedDevice))
        {
            if (removedDevice.CancelToken != null && !removedDevice.CancelToken.IsCancellationRequested)
            {
                removedDevice.CancelToken.Cancel();  // 取消与被移除设备关联的任务
                removedDevice.CancelToken.Dispose(); // 释放与 CancellationTokenSource 关联的资源
            }
        }
    }

    /// <summary>
    /// 返回所有设备
    /// </summary>
    /// <returns></returns>
    public ConcurrentDictionary<string, PassDevice> SelectAllDevices()
    {
        return PlatformOnlineDevicesDic;
    }

    public void semaphoreRelease()
    {
        semaphore.Release();
    }

    public void setRunning(bool running)
    {
        isRunning = running;
    }

    bool IPlatFormJobManager.isRunning()
    {
        return isRunning;
    }

    ConcurrentDictionary<string, PassDevice> IPlatFormJobManager.PlatformOnlineDevicesDic()
    {
        return PlatformOnlineDevicesDic;
    }

    SemaphoreSlim IPlatFormJobManager.semaphore()
    {
        return semaphore;
    }
}

public class PassDevice
{
    /// <summary>
    /// 设备对象
    /// </summary>
    public Device Device { get; set; }
    /// <summary>
    /// 客户端是否在线
    /// </summary>
    public bool IsOnline { get; set; } = false;
    /// <summary>
    /// 取消令牌
    /// </summary>
    public CancellationTokenSource CancelToken { get; set; }
}